<style type="text/css">
    .btnAnswer{
        background-image: none;
        background-color: red;
    }
</style>


<?php // echo( $object);exit;?>

<script language='javascript'>
    var img = '';
    var object = "";
    var formSlide;
    var containerTypeSM;
    var fObjectSM, fObjectTP ;
    var formQuestions;
    var _editor;
    var n = 0; //<-- usado para ir creando "name" de cada formulario dinamicamente
    var deletedAnswers = [];
    var grid;
    var formResource;
    var CFG;
    var formObject;
    var _question = null;
    var disableTabs = false;
    var screen = window.screen.width*.7;
    var _ObjectID = null;

    <?php if(isset($object)){?>
        _ObjectID = <?php echo $object->id;?>;
    <?php } ?>

    $(document).ready(function() {
        Ext.Loader.setConfig({enabled: true});
        Ext.Loader.setPath('Ext.ux', '../ux/');
        
        Ext.require([
            'Ext.grid.*',
            'Ext.data.*',
            'Ext.util.*',
            'Ext.toolbar.Paging',
            'Ext.ModelManager',
            'Ext.tip.QuickTipManager',
            'Ext.form.*',
            'Ext.layout.container.Column',
            'Ext.tab.*'
        ]);
        
        Ext.override(Ext.form.Panel, {
             clearForm:function(){
                Ext.each(this.getForm().getFields().items, function(field){
                    field.setValue('');
                    field.remove();
                });
             }
        });


        var id = 0;
        var win;
        var loadQuestions = false;

        if(_ObjectID){
            Ext.Ajax.request({
                url: BASE_URL+"objects/get",
                params:{id:_ObjectID},
                success: function(response, opts) {
                   var obj = Ext.decode(response.responseText);
                   object = obj.data;
                   _init(object);
                },
                failure: function(response, opts) {
                   console.log('server-side failure with status code ' + response.status);
                }
            });
        }
        else{
            _init(null)
        }

        function _init(object){
            if(object && object.test && object.test.id)   loadQuestions = true;

            CFG = Ext.decode('<?php echo json_encode($cfg); ?>');
            //store de recursos y archivos
            var stRequisites = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort:true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'objects/getRelatedObjects',
                    method: 'GET',
                   // extraParams: {id: object.id},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'},
                    {name: 'category_name', mapping: 'category_name', type: 'string'},
                    {name: 'type_name', mapping: 'type_name', type: 'string'},
                    {name: 'dcreated', mapping: 'dcreated', type: 'string'},
                    {name: 'dmodified', mapping: 'dmodified', type: 'string'},
                    {name: 'ucreated', mapping: 'ucreated', type: 'string'},
                    {name: 'umodified', mapping: 'umodified', type: 'string'}
                ]
            });
            var stTypeQuestions = new Ext.data.JsonStore({
                autoLoad: true,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'typequestions/loadList',
                    method: 'GET',
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'}
                ]
            });
            var stCategories = new Ext.data.JsonStore({
                autoLoad: true,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'categories/loadList',
                    method: 'GET',
                    extraParams: {type_objects_id: CFG.type_object_theme},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                        [
                            {name: 'id', mapping: 'id', type: 'string'},
                            {name: 'name', mapping: 'name', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ]
            });
            var stThemes = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'objects/loadList',
                    method: 'GET',
                    extraParams: {type_objects_id: CFG.type_object_theme},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                        [
                            {name: 'id', mapping: 'id', type: 'string'},
                            {name: 'name', mapping: 'name', type: 'string'},
                            {name: 'description', mapping: 'description', type: 'string'}
                        ]
            });
            var stPrevQuestions = new Ext.data.JsonStore({
                autoLoad:false,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'questions/loadList',
                    method: 'GET',
                  //  extraParams: {elem_test_id: object.test.id, removeHTML:true},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'},
                    {name: 'type_objects_id', mapping: 'type_objects_id', type: 'string'},
                    {name: 'type_questions_id', mapping: 'type_questions_id', type: 'string'},
                    {name: 'answers', mapping: 'answers', type: 'object'},
                    {name: 'innerAnswers', mapping: 'innerAnswers', type: 'object'}
                ]
            });
            var stAnswers = new Ext.data.JsonStore({
                autoLoad:false,
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'answers/loadList',
                    method: 'GET',
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'}
                ],
                listeners:{
                    load:function(){
                        formQuestions.getForm().findField("parent").setVisible(true);
                        if(_question && formQuestions.getForm().findField('parent')){
                            formQuestions.getForm().findField('parent').setValue(_question.parent);
                            _question = null;
                        }
                    }
                }
            });
            var stObjectStatus = new Ext.data.JsonStore({
                autoLoad: false,
                remoteSort: false,
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'name', mapping: 'name', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'}
                ],
                data:[
                    {id: CFG.object_enabled, name: "HABILITADO" },
                    {id: CFG.object_disabled, name: "DESHABILITADO" },
                    {id: CFG.object_develop, name: "DESARROLLO" },
                    {id: CFG.object_publish, name: "PUBLICAR" }
                ]
            });
            function updateObjectReferences(newObject){
                object = newObject;
                if(object && object.name){
                    if(Ext.getCmp('tabRequisites')) Ext.getCmp('tabRequisites').setDisabled(false);
                    if(Ext.getCmp('tabQuestions')) Ext.getCmp('tabQuestions').setDisabled(false);

                    formObject.getForm().url = BASE_URL+"objects/edit";
                    formObject.getForm().findField("id").setValue(object.id);
                    formObject.getForm().findField("type_objects_id").setValue(object.type_objects_id);
                    formObject.getForm().findField("name").setValue(object.name);
                    formObject.getForm().findField("description").setValue(object.description);
                    formObject.getForm().findField("ucreated").setValue(object.ucreated);
                    formObject.getForm().findField("dcreated").setValue(object.dcreated);
                    formObject.getForm().findField("umodified").setValue(object.umodified);
                    formObject.getForm().findField("dmodified").setValue(object.dmodified);
                    formObject.getForm().findField("category_id").setValue(object.category_id);

                    formObject.getForm().findField("status").setValue(object.status);
                    formObject.getForm().findField("version").setValue(object.version);
                    formObject.getForm().findField("status").setReadOnly(false);
                    
                    Ext.getCmp("featuredImageObject").setSrc(object.featuredImage);
                    
                    //configuramos el objeto como prueba
                    formTest.getForm().findField("type_objects_id").setValue(CFG.type_object_test);
                    //configuramos objects_id en prueba
                    formTest.getForm().findField("objects_id").setValue(object.id);
                    stRequisites.getProxy().extraParams = {id: object.id};
                    stRequisites.load();
                }
                
                //si el objeto tema posee prueba
                if(object && object.test && object.test.title){
                    formTest.getForm().url = BASE_URL+"test/edit";
                    formTest.getForm().findField("type_objects_id").setValue(object.test.type_objects_id);
                    formTest.getForm().findField("id").setValue(object.test.id);
                    formTest.getForm().findField("title").setValue(object.test.title);
                    formTest.getForm().findField("description").setValue(object.test.description);

                    stPrevQuestions.getProxy().extraParams = {elem_test_id: object.test.id, removeHTML:true};
                    stQuestions.getProxy().extraParams = {elem_test_id: object.test.id, innerQuestions:true};
                }
            }
            function generateUID(separator) {
                /// <summary>
                ///    Creates a unique id for identification purposes.
                /// </summary>
                /// <param name="separator" type="String" optional="true">
                /// The optional separator for grouping the generated segmants: default "-".    
                /// </param>

                var delim = separator || "-";

                function S4() {
                    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
                }

                return (S4() + S4() + delim + S4() + delim + S4() + delim + S4() + delim + S4() + S4() + S4());
            };
            function resetFullForm(dynamicForm){
                if(dynamicForm){
                    dynamicForm.getForm().reset();
                    dynamicForm.getForm().getFields().items.forEach(function(item){
                        var ct = item.up('container');
                        dynamicForm.remove(ct,true);
                    });
                    dynamicForm.getForm().getFields().items = [];
                }
                return;
            }
            function _sendQuestion(url){
                if(object.test && object.test.id){
                    var answers = [];
                    var question = {};
                    question.elem_test_id = object.test.id;
                    question.description = CKEDITOR.instances.ckeditor.document.getBody().getHtml();
                    question.type_questions_id = formQuestions.getForm().findField("type_questions_id").getValue();
                    question.id = formQuestions.getForm().findField("id").getValue();

                    question.parent = formQuestions.getForm().findField("parent").getValue();
                    question.type_object_parent_id = formQuestions.getForm().findField("type_object_parent_id").getValue();

                    //si esta visible..
                    if(Ext.getCmp('fObjectSM') && Ext.getCmp('fObjectSM').isVisible()){
                        var form =  Ext.getCmp('ctDinamico').getForm();
                        for(var i=0;i<=Ext.getCmp('ctDinamico').items.items.length;i++){
                            var answer = {};
                            if(form.findField("description_"+i)){
                                answer.description = form.findField("description_"+i).getValue();
                            }
                            if(form.findField("explication_"+i)){
                                answer.explication = form.findField("explication_"+i).getValue();
                            }
                            if(form.findField("value_"+i) && form.findField("value_"+i).getValue('on')){
                                answer.value = true;
                            }
                            if(form.findField("id_"+i)){
                                answer.id = form.findField("id_"+i).getValue();
                            }
                            if(typeof answer.description !== "undefined" && answer.description !== "")
                                answers.push(answer);
                        }
                        
                        //resetFullForm(Ext.getCmp('ctDinamico'));

                    }
                    else{
                        //si es Termino pareado
                        if(Ext.getCmp('fObjectTP') && Ext.getCmp('fObjectTP').isVisible()){
                            var form =  Ext.getCmp('ctDinamicoTP').getForm();
                            for(var i=0;i<=Ext.getCmp('ctDinamicoTP').items.items.length;i++){
                                var answer = {};
                                if(form.findField("description1_"+i)){
                                    answer.description1 = form.findField("description1_"+i).getValue();
                                }
                                if(form.findField("description2_"+i)){
                                    answer.description2 = form.findField("description2_"+i).getValue();
                                }
                                
                                if(form.findField("id1_"+i)){
                                    answer.id1 = form.findField("id1_"+i).getValue();
                                }
                                if(form.findField("id2_"+i)){
                                    answer.id2 = form.findField("id2_"+i).getValue();
                                }
                                if(typeof answer.description1 !== "undefined" && answer.description1 !== "")
                                    answers.push(answer);
                            }
                            
                            //resetFullForm(Ext.getCmp('ctDinamicoTP'));
                        }
                        //si es verdadero o falso
                        if(Ext.getCmp('ctVF').isVisible()){
                            var answer = {};
                            question.value =  formQuestions.getForm().findField("enunciadoValue").getValue();
                        }
                    }
                    question.answers = answers;
                    question.deletedAnswers = deletedAnswers;
                    Ext.Ajax.request({
                        url: url,
                        params:{
                            elem_test_id:question.elem_test_id,
                            type_questions_id:question.type_questions_id,
                            description:question.description,
                            question: Ext.encode(question)
                        },
                        success: function(response, opts) {
                           var res = Ext.decode(response.responseText);
                           if(res.success){
                                resetFullForm(Ext.getCmp('ctDinamico'));
                                resetFullForm(Ext.getCmp('ctDinamicoTP'));
                                formQuestions.getForm().reset();
                               //Ext.getCmp('ctDinamico').getForm().getFields().items = [];
                                        
                               _editor.setData("");
                               //actualizamos preguntas en contenedor
                               stQuestions.load();
                               stPrevQuestions.load();
                               win.hide();
                           }
                           else{
                                Ext.MessageBox.show({
                                    title: 'Error en la operaci\u00F3n',
                                    msg: _getErrorFromArray(res.errors),
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.ERROR,
                                    minWidth: 400
                                });
                                return;
                           }
                        },
                        failure: function(response, opts) {
                           alert('server-side failure with status code ' + response.status);
                        }
                    });
                }
                else{
                    alert("Debe definir la prueba en el formulario superior antes de crear las preguntas.");
                }
            }
            //retorna formulario de preguntas de un tipo determinado
            function _getSMAnswerFrom(k,answer,type){
                //si es SM
                var _id = generateUID();
                if(type== 3){
                    var checked = false;
                    var value = {};
                    if(answer){
                        value.id = answer.id;
                        value.description = answer.description;
                        value.explication = answer.explication;
                        checked = (answer.value === "1");
                    }
                    else{
                        value.id = "";
                        value.description = "";
                        value.explication = "";
                    }
                
                    return {
                        layout: 'hbox',
                        xtype: 'container',
                        border:false,
                        frame: false,
                        items:[
                            {
                                xtype:'hidden',
                                name:'id_'+k,
                                value:value.id
                            },
                            {
                                xtype:'hidden',
                                name:'explication_'+k,
                                value:value.explication
                            },
                            {
                                xtype: 'radiofield',
                                margin: '0 0 0 10'
                            },
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                value:value.description,
                                name:'description_'+k
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10',
                                checked:checked,
                                name:'value_'+k
                            },
                            ,
                            {
                                xtype: 'button',
                                margin: '0 0 0 10',
                                text:'Explicación',
                                iconCls: 'x-icon-add',
                                handler:function(btn){
                                    var winExplication = new Ext.Window({
                                        title: 'Explicación',
                                        resizable: false,
                                        width: 300,
                                        height: 200,
                                        forceFit: true,
                                        frame: false,
                                        layout: 'fit',
                                        modal: true,
                                        plain: true,
                                        buttonAlign: 'center',
                                        items: [
                                            {
                                                xtype:'textarea',
                                                margin:'10',
                                                id:_id,
                                                value:Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).getValue()
                                            }
                                        ],
                                        closable: false,
                                        buttons: [
                                            {
                                                text: 'Cerrar',
                                                iconCls: 'x-icon-cancel',
                                                handler: function() {
                                                    Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                                    winExplication.hide();
                                                }
                                            }
                                        ]
                                    });

                                    winExplication.on('close', function() {
                                        Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                        win.toggleCollapse();
                                    });
                                    winExplication.on('minimize', function() {
                                        Ext.getCmp('ctDinamico').getForm().findField('explication_'+k).setValue(Ext.getCmp(_id).getValue());
                                        win.toggleCollapse();
                                    });
                                    winExplication.show();
                                }
                            },
                            {
                                xtype: 'button',
                                margin: '0 0 0 10',
                                iconCls: 'x-icon-delete',
                                handler:function(btn){
                                    var ct = btn.up('container');
                                    deletedAnswers.push(Ext.getCmp('ctDinamico').getForm().findField('id_'+k).getValue());
                                    Ext.getCmp('ctDinamico').remove(ct,true);
                                }
                            }
                        ]
                    };
                }
                else{//respuesta termino pareado
                    if(type == 2){
                        var value = {};
                        value.inner = {};

                        if(answer){
                            value.id = answer.id;
                            value.description = answer.description;
                            checked = (answer.value === "1");

                            value.inner.id = answer.answer.id;
                            value.inner.description = answer.answer.description;
                        }
                        else{
                            value.id = "";
                            value.description = "";
                            value.inner.id = "";
                            value.inner.description = "";
                        }
                    
                        return {
                            layout: 'hbox',
                            xtype: 'container',
                            border:false,
                            frame: false,
                            items:[
                                {
                                    xtype:'hidden',
                                    name:'id1_'+k,
                                    value:value.id
                                },
                                {
                                    xtype:'hidden',
                                    name:'id2_'+k,
                                    value:value.inner.id
                                },
                                {
                                    xtype: 'textfield',
                                    margin: '0 0 0 10',
                                    fieldLabel:'Termino 1',
                                    width:200,
                                    value:value.description,
                                    name:'description1_'+k
                                },
                                {
                                    xtype: 'textfield',
                                    margin: '0 0 0 10',
                                    fieldLabel:'Termino 2',
                                    width:200,
                                    value:value.inner.description,
                                    name:'description2_'+k
                                },
                                {
                                    xtype: 'button',
                                    margin: '0 0 0 10',
                                    iconCls: 'x-icon-delete',
                                    handler:function(btn){
                                        var ct = btn.up('container');
                                        deletedAnswers.push(Ext.getCmp('ctDinamicoTP').getForm().findField('id1_'+k).getValue());
                                        deletedAnswers.push(Ext.getCmp('ctDinamicoTP').getForm().findField('id2_'+k).getValue());
                                        Ext.getCmp('ctDinamicoTP').remove(ct,true);
                                    }
                                }
                            ]
                        };
                    }
                }
            }
            var stQuestions = new Ext.data.JsonStore({
                remoteSort: true,
                proxy: new Ext.data.HttpProxy({
                    url: BASE_URL + 'questions/loadList',
                    method: 'GET',
                  //  extraParams: {elem_test_id: object.test.id, innerQuestions:true},
                    reader: {
                        type: 'json',
                        root: 'rows',
                        totalProperty: 'results'
                    }
                }),
                fields:
                [
                    {name: 'id', mapping: 'id', type: 'string'},
                    {name: 'description', mapping: 'description', type: 'string'},
                    {name: 'type_objects_id', mapping: 'type_objects_id', type: 'string'},
                    {name: 'type_questions_id', mapping: 'type_questions_id', type: 'string'},
                    {name: 'answers', mapping: 'answers', type: 'object'},
                    {name: 'innerAnswers', mapping: 'innerAnswers', type: 'object'},
                    {name: 'deep', mapping: 'deep', type: 'object'}
                ],
                listeners:{
                    load:function(store, records, options){
                        console.log(records)
                        var list = "";
                        var nQ = 1;
                        var rendered = new Array();
                        jQuery.each(records,function(i,item){
                            item = item.data;
                            
                            var buttonCopiar = "<button class='btn btnCopy' id='"+item.id+"' title='Copiar' alt='Copiar'><i class='icon-file'></i></button>";
                            var buttonEliminar = "<button class='btn btnRemove' id='"+item.id+"' title='Eliminar' alt='Copiar'><i class='icon-trash'></i></button>";
                            var buttonEditar = "<button class='btn btnEdit' id='"+item.id+"' title='Editar' alt='Copiar'><i class='icon-edit'></i></button>";
                            var buttons = buttonEliminar+buttonEditar+buttonCopiar;
                            var li = "<li style='border:none;' class='li_question'><div style='padding:10px;border:1px solid gray;margin-left:"+(item.deep*30)+"px;' class='elem_question_case'><div><span class='test_question_number'>"+(nQ++)+".- </span>"+item.description+"</div>"+buttons+"<ul style='margin-top:10px;'>";
                            var select = "";

                            //terminos pareados
                            if(item.type_questions_id == 2){
                                //creamos un select
                                jQuery.each(item.innerAnswers,function(k,inner){
                                    select = select + "<option>"+inner.description+"</option>";
                                });
                                select = "<select style='width:120px;float:left;height:20px;'>"+select+"</select>";
                            }

                            jQuery.each(item.answers,function(i,answer){
                               // console.log(item)
                                //seleccion multiple
                                if(item.type_questions_id == 3)
                                    li = li + "<li><input type='checkbox'/><label>"+answer.description+"</label></li>";
                                //terminos pareados
                                if(item.type_questions_id == 2){
                                    li = li + "<li><label style='width:150px;float:left;height:20px;'>"+answer.description+"</label>"+select+"</li>";
                                }
                            });
                            //cerramos lista de respuestas
                            li = li+"</ul>";
                            //cerramos li global de pregunta
                            li = li+"</div></li>";
                            list = list+li;
                        });
                        jQuery("#divCreatedQuestions").html(list);
                        jQuery(".btnCopy").on("click",function(){
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/duplicate',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                   var obj = Ext.decode(response.responseText);
                                   //actualizamos preguntas en contenedor
                                   stQuestions.load();
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                        jQuery(".btnRemove").on("click",function(){
                            var _this = this;
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/del',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                   var res = Ext.decode(response.responseText);
                                   if(res.success){
                                        jQuery(_this).parent().slideUp("slow",function(){
                                            stQuestions.load();
                                        });
                                   }
                                   else{
                                       Ext.MessageBox.show({
                                            title: 'Error en la operaci\u00F3n',
                                            msg: res.msg+"<br>"+_getErrorFromArray(res.errors),
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.ERROR,
                                            minWidth: 400
                                        });
                                   }
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                        jQuery(".btnEdit").on("click",function(){
                            var id = jQuery(this).attr("id");
                            Ext.Ajax.request({
                                url: BASE_URL+'questions/get',
                                params:{
                                    id:id
                                },
                                success: function(response, opts) {
                                    var res = Ext.decode(response.responseText);
                                    var question = res.data;
                                    _question = question;
                                   //limpiando contenedor dinamico si o si
                                    resetFullForm(Ext.getCmp('ctDinamico'));
                                    resetFullForm(Ext.getCmp('ctDinamicoTP'));
                                    add(question);
                                },
                                failure: function(response, opts) {
                                   console.log('server-side failure with status code ' + response.status);
                                }
                            });
                        });
                    }
                }
            });
            formObject = Ext.create('Ext.form.Panel', {
                bodyPadding: 40,
                width:'100%',
                url: BASE_URL + 'objects/add',
                layout:'hbox',
                fieldDefaults: {
                    labelAlign: 'left',
                    labelWidth: 120,
                    anchor: '30%'
                },
                items: [
                    {
                        xtype:'container',
                       // layout:'vbox',
                        flex:1,
                        items:[
                            {
                                xtype: 'image',
                                height: 200,
                                width:200,
                                id: 'featuredImageObject'
                            }
                        ]
                    },
                    {
                        xtype:'container',
                        layout:'vbox',
                        flex:2,
                        items:[
                            {
                                xtype: 'hidden',
                                name: 'featuredImage'
                            },
                            {
                                xtype: 'hidden',
                                name: 'type_objects_id',
                                value:CFG.type_object_cliniccase
                            },
                            {
                                xtype: 'hidden',
                                name: 'id'
                            },
                            {
                                xtype: 'textfield',
                                name: 'name',
                                fieldLabel: 'Nombre Tema'
                            },
                            {
                                xtype: 'textarea',
                                name: 'description',
                                fieldLabel: 'Descripción Tema'
                            },
                            {
                                xtype: 'combo',
                                store: stCategories,
                                editable: false,
                                displayField: 'name',
                                name: 'category_id',
                                valueField: 'id',
                                fieldLabel: 'Categoría',
                                queryMode: 'local'
                            },
                            {
                                xtype: 'button',
                                //width: 20,
                                margin:'5 0 10 195',
                                iconCls: 'x-icon-image-edit',
                                text: 'Configurar Imagen',
                                handler: function() {
                                    var finderx = new CKFinder();
                                    finderx.selectActionFunction = function(url, data) {
                                        Ext.getCmp('featuredImageObject').setSrc(url);
                                        formObject.getForm().findField("featuredImage").setValue(url);
                                    };
                                    finderx.popup();
                                }
                            },
                            {
                                xtype: 'combo',
                                store: stObjectStatus,
                                editable: false,
                                readOnly:object?false:true,
                                displayField: 'name',
                                name: 'status',
                                valueField: 'id',
                                fieldLabel: 'Estado',
                                queryMode: 'local',
                                listeners:{
                                    select:function(a,b,c){
                                        if(object && object.id){
                                            b = b[0];
                                            var status = b.get('id');
                                            Ext.Ajax.request({
                                                url: BASE_URL + 'objects/changeStatus',
                                                method: 'POST',
                                                params: {id: object.id, status:status},
                                                success:function(action) {   
                                                    var res = Ext.decode(action.responseText);
                                                    if(res.success){
                                                        object.version = res.data.version;
                                                        formObject.getForm().findField("version").setValue(object.version);
                                                        Ext.MessageBox.show({
                                                            title: 'Operacion exitosa',
                                                            msg: "Objeto actualizado",
                                                            buttons: Ext.MessageBox.OK,
                                                            icon: Ext.MessageBox.SUCCESS,
                                                            minWidth:300
                                                        });
                                                    }
                                                    else{
                                                        Ext.MessageBox.show({
                                                            title: 'Error en la operaci\u00F3n',
                                                            msg: _getErrorFromArray(res.errors),
                                                            buttons: Ext.MessageBox.OK,
                                                            icon: Ext.MessageBox.ERROR,
                                                            minWidth:300
                                                        });
                                                    }
                                                },
                                                failure:function(form, action) {     
                                                    if(action.failureType == 'load'){                            
                                                        Ext.Msg.alert('Error', action.result.reason);
                                                    } 
                                                    else{
                                                        Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                                                    } 
                                                }
                                            });
                                        }
                                        
                                    }
                                }
                            },
                            {
                                xtype: 'textfield',
                                readOnly: true,
                                name:'ucreated',
                                fieldLabel: 'Creado por'
                            },
                            {
                                xtype: 'textfield',
                                name:'dcreated',
                                readOnly: true,
                                fieldLabel: 'Fecha Creación'
                            },
                            {
                                xtype: 'textfield',
                                readOnly: true,
                                name:'umodified',
                                fieldLabel: 'Modificado por'
                            },
                            {
                                xtype: 'textfield',
                                name:'dmodified',
                                readOnly:true,
                                fieldLabel: 'Fecha Modificación'
                            },
                            {
                                xtype: 'textfield',
                                name:'version',
                                readOnly:true,
                                fieldLabel: 'VERSION'
                            }
                        ]
                    }
                    
                ],
                buttons: [
                    {
                        xtype: 'button',
                        margin: '20',
                        text: 'Guardar',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            formObject.getForm().submit({
                                success: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    if(!object){
                                        updateObjectReferences(res.data.object)
                                        Ext.MessageBox.show({
                                            title: 'Operación exitosa',
                                            msg: "Caso clínico creado en forma exitosa",
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.INFO,
                                            minWidth: 300
                                        });
                                    }
                                    else{
                                        formObject.getForm().findField("dmodified").setValue(res.data.dmodified);
                                        formObject.getForm().findField("umodified").setValue(res.data.umodified);
                                    }
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
            var formTest = Ext.create('Ext.form.Panel', {
                collapsible:true,
                collapsed:true,
                title:'Detalle Caso',
                border: 0,
                url: BASE_URL + 'test/add',
                items: [
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'type_objects_id'
                    },
                    {
                        xtype: 'hidden',
                        margin: '0 0 0 30',
                        name: 'objects_id'
                    },
                    {
                        xtype: 'hidden',
                        name: 'id'
                    },
                    {
                        xtype: 'textfield',
                        margin: '0 0 0 30',
                        name: 'title',
                        fieldLabel: 'Título'
                    },
                    {
                        xtype: 'textarea',
                        margin: '0 0 0 30',
                        name: 'description',
                        fieldLabel: 'Descripción'
                    },
                    {
                        xtype:'button',
                        margin: '0 0 10 105',
                        text:'Guardar Cambios',
                        iconCls: 'x-icon-save',
                        handler: function(a, b, c) {
                            formTest.getForm().submit({
                                success: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    updateObjectReferences(res.data.object);
                                    Ext.MessageBox.show({
                                        title: 'Operacion exitosa',
                                        msg: "Prueba creada en forma exitosa.",
                                        buttons: Ext.MessageBox.OK,
                                        minWidth: 300
                                    });
                                },
                                failure: function(form, action) {
                                    var res = Ext.decode(action.response.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Error en la operaci\u00F3n',
                                        msg: _getErrorFromArray(res.errors),
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.ERROR,
                                        minWidth: 300
                                    });
                                }
                            });
                        }
                    }
                ]
            });
    ////      formulario de seleccion multiple  
            fObjectSM = {
                id:'fObjectSM',
                xtype:'form',
                frame:false,
                border: false,
                visible:false,
                url: BASE_URL + 'questions/add',
                layout:'vbox',
                items: [
                    {
                        xtype: 'form',
                        layout: 'vbox',
                        frame:false,
                        border: false,
                        id:'ctDinamico',
                        items: [_getSMAnswerFrom(n,false,3)]
                    },
                    {
                        xtype: 'container',
                        layout: 'hbox',
                     //   id:'ctAddForms',
                        items:[
                            {
                                xtype: 'radiofield',
                                margin: '0 0 0 10'
                            },
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                name: 'description_dinamyc',
                                fieldStyle: 'color:#C7C7C7;',
                                handleMouseEvents: true,
                                readOnly:true,
                                value:'Haz clic para añadir una opción',
                                listeners:{
                                    render: function(cmp) { 
                                        this.getEl().on('mousedown', function(a,b,c){
                                            n++;//aumentamos contador de formulario dinamico
                                            Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,false,3));
                                        }); 
                                    }
                                }
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10'
                            }
                        ]
                    }
                ]
            };
            //formulario terminos pareados
            fObjectTP = {
                id:'fObjectTP',
                xtype:'form',
                frame:false,
                border: false,
                visible:false,
                url: BASE_URL + 'questions/add',
                layout:'vbox',
                items: [
                    {
                        xtype: 'form',
                        layout: 'vbox',
                        frame:false,
                        border: false,
                        id:'ctDinamicoTP',
                        items: [_getSMAnswerFrom(n,false,2)]
                    },
                    {
                        xtype: 'container',
                        layout: 'hbox',
                     //   id:'ctAddForms',
                        items:[
                            {
                                xtype: 'textfield',
                                margin: '0 0 0 10',
                                name: 'description_dinamyc',
                                fieldStyle: 'color:#C7C7C7;',
                                fieldLabel:'Nuevo',
                                handleMouseEvents: true,
                                readOnly:true,
                                value:'Haz clic para añadir una opción',
                                listeners:{
                                    render: function(cmp) { 
                                        this.getEl().on('mousedown', function(a,b,c){
                                            n++;//aumentamos contador de formulario dinamico
                                            Ext.getCmp('ctDinamicoTP').add(_getSMAnswerFrom(n,false,2));
                                        }); 
                                    }
                                }
                            },
                            {
                                xtype: 'checkboxfield',
                                margin: '0 0 0 10'
                            }
                        ]
                    }
                ]
            };
            function add(question) {
                deletedAnswers = [];
                //solo si no existe lo creamos
                if(!win){
                    formQuestions = Ext.create('Ext.form.Panel', {
                        border: 0,
                        height:400,
                        autoScroll:true,
                        scroll:true,
                        margin: '20 0 30 20',
                        url: BASE_URL + 'questions/add',
                        items: [
                            {
                                xtype: 'hidden',
                                name: 'id'
                            },
                            {
                                xtype: 'hidden',
                                name: 'type_object_parent_id',
                                value:CFG.type_object_answer
                            },
                            {
                                xtype:'container',
                                layout:'hbox',
                                items:[
                                    {
                                        xtype: 'label',
                                        text: 'Enunciado Pregunta',
                                        margin: '0 0 0 0',
                                        name:'description',
                                        value: 'Enunciado Pregunta'
                                    }
                                ]
                            },
                            {
                                xtype: 'container',
                                html:'<div class="elem_question_title" id="ckeditor"></div>',
                                id: 'ckeditorContainer'
                            },
                            {
                                xtype      : 'fieldcontainer',
                                fieldLabel : 'Verdadero?',
                                id:'ctVF',
                                hidden:true,
                                defaultType: 'checkboxfield',
                                items: [
                                    {
                                        xtype: 'checkboxfield',
                                        width:200,
                                        checked:false,
                                        inputValue: false,
                                        name:'enunciadoValue'
                                    }
                                ]
                            },
                            {
                                xtype: 'combo',
                                store: stTypeQuestions,
                                editable: false,
                                readOnly:true,
                                margin: '20 0 0 0',
                                displayField: 'name',
                                name: 'type_questions_id',
                                valueField: 'id',
                                fieldLabel: 'Tipo Pregunta',
                                queryMode: 'local',
                                listeners:{
                                    select:function(a,records){
                                        if(records[0].get('id') == 3){
                                            formQuestions.getForm().findField('parentQuestion').setVisible(true);
                                            //formQuestions.getForm().findField('parentQuestion').setValue(question.parentAnswer.elem_questions_id);    
                                        }
                                        /*
                                        
                                        */
                                    },
                                    change:function(a,b,c){
                                        console.log('change?')
                                        //ocultamos todos los formularios
                                        if(Ext.getCmp('fObjectSM')){
                                            Ext.getCmp('fObjectSM').setVisible(false);
                                        }
                                        if(Ext.getCmp('fObjectTP')){
                                            Ext.getCmp('fObjectTP').setVisible(false);
                                        }
                                        if(Ext.getCmp("ctVF")){
                                            Ext.getCmp("ctVF").setVisible(false);
                                        }
                                        //mostramos el que selecciono solamente
                                        if(b == 3){
                                            if(!Ext.getCmp('fObjectSM')){
                                                Ext.getCmp("ctQuestionForm").add(fObjectSM);
                                            }
                                            Ext.getCmp('fObjectSM').setVisible(true);
                                        }
                                        else{
                                            //terminos pareados
                                            if(b == 2){
                                                if(!Ext.getCmp('fObjectTP')){
                                                    Ext.getCmp("ctQuestionForm").add(fObjectTP);
                                                }
                                                Ext.getCmp('fObjectTP').setVisible(true);
                                            }
                                            else{
                                                //verdadero falso
                                                if(b == 1){
                                                    if(formQuestions){
                                                        Ext.getCmp("ctVF").setVisible(true);
                                                    }
                                                }
                                            }
                                        }
                                        
                                        Ext.getCmp("ctQuestionForm").doLayout();
                                    }
                                }
                            },
                            {
                                xtype: 'combo',
                                width:500,
                                store: stPrevQuestions,
                                editable: false,
                                hidden:true,
                                displayField: 'description',
                                name: 'parentQuestion',
                                valueField: 'id',
                                fieldLabel: 'Asociar con',
                                listeners:{
                                    change:function(a,id,c){
                                        //console.log('fired');
                                        if(id == formQuestions.getForm().findField("id").getValue()){
                                            Ext.MessageBox.show({
                                                title: 'Error en la operaci\u00F3n',
                                                msg: "La pregunta no puede depender de si misma",
                                                buttons: Ext.MessageBox.OK,
                                                icon: Ext.MessageBox.ERROR,
                                                minWidth: 300
                                            });
                                            formQuestions.getForm().findField("parent").setValue("");
                                        }
                                        else{
                                            stAnswers.load({ params: { question_id: id } });
                                        }    

                                    }
                                },
                                queryMode: 'local'
                            },
                            {
                                xtype: 'combo',
                                width:500,
                                store: stAnswers,
                                editable: false,
                                hidden:true,
                                displayField: 'description',
                                name: 'parent',
                                valueField: 'id',
                                fieldLabel: 'Respuesta padre',
                                listeners:{
                                    select:function(a,b,c){
                                        var answer = b[0].data;
                                    }
                                },
                                queryMode: 'local'
                            },
                            {
                                xtype: 'container',
                                margin: '20 0 0 0',
                                autoScroll:true,
                                scroll:true,
                                frame:false,
                                border: false,
                                id: 'ctQuestionForm'
                            }
                        ]
                    });

                    win = new Ext.Window({
                        title: 'Pregunta',
                        resizable: false,
                        width: 550,
                        height: 600,
                        forceFit: true,
                        frame: false,
                        layout: 'fit',
                        modal: false,
                        plain: true,
                        buttonAlign: 'center',
                        items: formQuestions,
                        closable: false,
                        buttons: [{
                                text: 'Guardar',
                                iconCls: 'x-icon-save',
                                handler: function() {
                                    if(object.test && object.test.id){
                                        _sendQuestion(formQuestions.getForm().url);
                                    }
                                    else{
                                        alert("Debe definir la prueba en el formulario superior antes de crear las preguntas.");
                                    }
                                }
                            }, {
                                text: 'Cerrar',
                                iconCls: 'x-icon-cancel',
                                handler: function() {
                                    formQuestions.getForm().findField('parent').setValue("");
                                    win.hide();
                                }
                            }]
                    });

                    win.on('close', function() {
                        win.toggleCollapse();
                    });
                    win.on('minimize', function() {
                        win.toggleCollapse();
                    });

                }
                
                win.on("render",function(){
                    formQuestions.on("render",function(){
                        if(!_editor){
                            _editor = CKEDITOR.replace( 'ckeditor' , _editorCFG);
                            CKFinder.setupCKEditor(_editor, _editorCFG);
                            _editor.setData("");
                        }

                        resetFullForm(Ext.getCmp('ctDinamico'));
                        resetFullForm(Ext.getCmp('ctDinamicoTP'));
                         
                        formQuestions.getForm().reset();

                        if(question){
                            _editor.setData(question.description);
                            if(Ext.getCmp('ctDinamico')){
                                jQuery.each(question.answers,function(i,answer){
                                    n++;
                                    Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,answer,3));
                                });
                            }

                            formQuestions.getForm().findField("id").setValue(question.id);
                            formQuestions.getForm().findField("type_questions_id").setValue(question.type_questions_id);
                            formQuestions.getForm().findField('type_questions_id').setReadOnly(true);

                            if(question.parent != "0"){
                                formQuestions.getForm().findField('parentQuestion').setVisible(true);
                                formQuestions.getForm().findField('parentQuestion').setValue(question.parentAnswer.elem_questions_id);
                                formQuestions.getForm().findField('parent').setVisible(true);
                            }
                            else{
                                formQuestions.getForm().findField('parentQuestion').setVisible(false);
                                formQuestions.getForm().findField('parent').setVisible(false);
                            }
                            if(question.type_questions_id == 1){
                                formQuestions.getForm().findField("enunciadoValue").setValue(question.value?true:false);
                            }

                        }
                    });
                });

                win.show();

                //limpiando contenedor dinamico si o si
                resetFullForm(Ext.getCmp('ctDinamico'));
                resetFullForm(Ext.getCmp('ctDinamicoTP'));

                formQuestions.getForm().reset();

                n = 0;
                

                if(question){
                    formQuestions.getForm().url = BASE_URL+"questions/edit";
                    _editor.setData(question.description);
                    formQuestions.getForm().findField("id").setValue(question.id);
                    formQuestions.getForm().findField("type_questions_id").setValue(question.type_questions_id);

                    
                    //if(question.parentAnswer){
                    if(question.parent != "0"){
                        formQuestions.getForm().findField('parentQuestion').setVisible(true);
                        formQuestions.getForm().findField('parent').setVisible(true);
                        formQuestions.getForm().findField('parentQuestion').setValue(question.parentAnswer.elem_questions_id);
                        
                    }
                    else{
                        formQuestions.getForm().findField('parentQuestion').setVisible(false);
                        formQuestions.getForm().findField('parent').setVisible(false);
                    }

                    

                    //formulario respuestas tipo SM
                    if(Ext.getCmp('ctDinamico') && question.type_questions_id == 3){
                        jQuery.each(question.answers,function(i,answer){
                            n++;
                            Ext.getCmp('ctDinamico').add(_getSMAnswerFrom(n,answer,question.type_questions_id));
                        });
                    }
                    //formulario respuestas tipo TP
                    if(Ext.getCmp('ctDinamicoTP') && question.type_questions_id == 2){
                        jQuery.each(question.answers,function(i,answer){
                            n++;
                            Ext.getCmp('ctDinamicoTP').add(_getSMAnswerFrom(n,answer,question.type_questions_id));
                        });
                    }
                    //formulario VF
                    if(question.type_questions_id == 1){
                        Ext.getCmp('ctVF').setVisible(true);
                        if(question.value === "1")
                            formQuestions.getForm().findField("enunciadoValue").setValue(true);
                        else formQuestions.getForm().findField("enunciadoValue").setValue(false);
                    }
                }
                else{
                    _editor.setData("");
                    formQuestions.getForm().url = BASE_URL+"questions/add";
                    formQuestions.getForm().findField('type_questions_id').setReadOnly(false);
                }
            }
            function addRequisite(record) {
                if(object && object.id){
                    formResource = new Ext.FormPanel({
                        anchor: '100%',
                        url: BASE_URL + 'objects/relationate',
                        layout: 'column',
                        frame: false,
                        bodyStyle: 'padding:5px 5px 0',
                        items: [{
                                xtype: 'container',
                                layout: 'anchor',
                                items: [
                                    {
                                        xtype:'hidden',
                                        name:'o1_id',
                                        value:object.id
                                    },
                                    {
                                        xtype: 'combo',
                                        store: stCategories,
                                        editable: false,
                                        displayField: 'name',
                                        name: 'category_id',
                                        valueField: 'id',
                                        fieldLabel: 'Categoría',
                                        queryMode: 'local',
                                        listeners:{
                                            change:function(a,id,c){
                                                stThemes.load({ params: { category_id: id } });
                                            }
                                        }
                                    },
                                    {
                                        xtype: 'combo',
                                        store: stThemes,
                                        editable: false,
                                        displayField: 'name',
                                        name: 'o2_id',
                                        valueField: 'id',
                                        fieldLabel: 'Tema',
                                        queryMode: 'local'
                                    }
                                ]
                            }]
                    });

                    var winRes = new Ext.Window({
                        title: 'Asociar Pre-requisito',
                        resizable: false,
                        width: 400,
                        height: 200,
                        forceFit: true,
                        frame: false,
                        layout: 'fit',
                        modal: true,
                        plain: true,
                        buttonAlign: 'center',
                        items: formResource,
                        closable: true,
                        buttons: [{
                                text: 'Guardar',
                                iconCls: 'x-icon-save',
                                handler: function() {
                                    if(object && object.id){
                                        formResource.getForm().submit({
                                            waitMsg: 'Enviando datos...',
                                            success: function(form, action) {
                                                stRequisites.load();
                                                winRes.hide();
                                            },
                                            failure: function(form, action) {
                                                var res = Ext.decode(action.response.responseText);
                                                Ext.MessageBox.show({
                                                    title: 'Error en la operaci\u00F3n',
                                                    msg: _getErrorFromArray(res.errors),
                                                    buttons: Ext.MessageBox.OK,
                                                    icon: Ext.MessageBox.ERROR,
                                                    minWidth: 300
                                                });
                                            }
                                        });
                                    }
                                    else{
                                        alert("Debe definir el Caso clínico antes de crear asociar Temas como pre-requisito.");
                                    }
                                    
                                }
                            }, {
                                text: 'Cancelar',
                                iconCls: 'x-icon-cancel',
                                handler: function() {
                                    winRes.hide();
                                }
                            }]
                    });
                    winRes.on('minimize', function() {
                        win.toggleCollapse();
                    });
                    formResource.getForm().reset();
                    winRes.show();
                }
                else{
                    Ext.MessageBox.show({
                        title: 'Error en la operaci\u00F3n',
                        msg: "Primero debe crear el caso clínico antes de asociar pre-requisitos de Temas",
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR,
                        minWidth: 300
                    });
                }
            }
            grid = Ext.create('Ext.grid.Panel', {
                columnLines:true,
                remoteSort:true,
                loadMask: true,
                fit:true,
                forceFit:true,
                height: 500,
                width: '100%',
                selModel: new Ext.selection.RowModel({singleSelect: true}),
                dockedItems: [
                    {
                        xtype: 'pagingtoolbar',
                        store: stRequisites,
                        dock: 'bottom',
                        displayInfo: true
                    }, 
                    {
                        xtype: 'toolbar',
                        dock: 'top',
                        defaults: {
                            labelStyle: 'font-weight:bold;'
                        },
                        items: [
                            {
                                id: 'add',
                                iconCls: 'x-icon-add',
                                text: 'Asociar Tema',
                                handler: function() {
                                    addRequisite();
                                }
                            }, 
                            {
                                id: 'del',
                                tooltip: 'Eliminar requisito',
                                iconCls: 'x-icon-delete',
                                text: 'Eliminar',
                                handler: function() {
                                    if (!grid.getSelectionModel().hasSelection()) {
                                        Ext.Msg.alert('Error', 'Primero debe seleccionar un registro.');
                                        return;
                                    }
                                    var selModel = grid.getSelectionModel().getSelection();
                                    var id = selModel[0].data.id;
                                    Ext.Msg.show({
                                        title: 'Confirme',
                                        msg: '¿Desea eliminar el requisito ' + selModel[0].data.name + '?',
                                        buttons: Ext.Msg.YESNO,
                                        fn: function(btn) {
                                            if (btn == 'yes') {
                                                Ext.Ajax.request({
                                                    url: BASE_URL + 'objects/delRelation',
                                                    method: 'POST',
                                                    params: {o2_id: id, id:object.id},
                                                    success:function(action) {   
                                                        var res = Ext.decode(action.responseText);
                                                        if(res.success){
                                                            grid.getStore().loadPage(1);  
                                                        }
                                                        else{
                                                            Ext.MessageBox.show({
                                                                title: 'Error en la operaci\u00F3n',
                                                                msg: _getErrorFromArray(res.errors),
                                                                buttons: Ext.MessageBox.OK,
                                                                icon: Ext.MessageBox.ERROR,
                                                                minWidth:300
                                                            });
                                                        }
                                                    },
                                                    failure:function(form, action) {     
                                                        if(action.failureType == 'load'){                            
                                                            Ext.Msg.alert('Error', action.result.reason);
                                                        } 
                                                        else{
                                                            Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                                                        } 
                                                    }
                                                });
                                                
                                            }
                                        }
                                    });
                                }
                            }
                        ]
                    }
                ],
                store: stRequisites,
                columns: [
                    {
                        header: 'Tipo',
                        dataIndex: 'type_name'
                    },
                    {
                        header: 'Categoría',
                        dataIndex: 'category_name'
                    },
                    {
                        header: 'Nombre',
                        dataIndex: 'name'
                    },
                    {
                        header: 'Descripción',
                        dataIndex: 'description'
                    }, {
                        header: 'F. Modificación',
                        dataIndex: 'dmodified'
                    }, {
                        header: 'F. Creación',
                        dataIndex: 'dcreated'
                    }, 
                    {
                        header: 'Creado por',
                        dataIndex: 'ucreated'
                    }, 
                    {
                        header: 'Modificado por',
                        dataIndex: 'umodified'
                    }
                ]
            });
            function main(){
                if(object){
                    updateObjectReferences(object);
                }
                else{
                    disableTabs = true;
                }
                Ext.create('Ext.tab.Panel', {
                    width: '100%',
                    id:'mainPanel',
                    renderTo: 'tab-panel',
                    items: [
                        {
                            title: 'Datos Generales',
                            items: formObject
                        },
                        {
                            title: 'Pre-requisitos',
                            id:'tabRequisites',
                            disabled:disableTabs,
                            items: grid
                        },
                        {
                            title: 'Caso Clínico',
                            id:'tabQuestions',
                            disabled:disableTabs,
                            items: [
                                formTest,
                                {
                                    xtype:'form',
                                    collapsible:true,
                                    id:'ctAllquestions',
                                    title:'Panel de Preguntas',
                                    bodyPadding:20,
                                    height:700,
                                    autoScroll:true,
                                    scroll:true,
                                    items:[
                                        {
                                            xtype:'button',
                                            margin: '0 0 10 105',
                                            text:'Nueva Pregunta XXX',
                                            iconCls: 'x-icon-add',
                                            handler: function(a, b, c) {
                                                if(object.test)
                                                    add();
                                                else{
                                                    Ext.Msg.alert('Error', 'Primero debe crear [Detalle Caso]'); 
                                                }
                                            }
                                        },
                                        {
                                            xtype: 'container',
                                            html:'<ol class="test_questions" id="divCreatedQuestions" style="margin-left;border:none;'+screen+'px;"></ol>',
                                            id: 'ctCreatedQuestions'
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    listeners: {
                        tabchange: function(tabPanel, newTab, oldTab, eOpts)  {
                            if(!object){
                                return false;
                            }
                        }
                    }
                });
                //al cargar container de preguntas se cargan las preguntas ohhhhhh
                Ext.getCmp('ctCreatedQuestions').on("render",function(){
                    stPrevQuestions.load();
                    stQuestions.load();
                });
            }

            main();
        
        }
    });
</script>

<input id="hd_context" type="hidden" value="<?php echo $breadcumb; ?>"/>
<ul class='ul_page' style="margin:0px;/*background-color: #237FCB;*/">
    <li id="tab-panel"></li>
</ul>

</div>

